package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.po.User;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;
    @Override
    public User getUserByIdByPass(String userId, String password) throws Exception{
        String sql = "SELECT * FROM user WHERE userId=? AND password =? ";
        User user = new User();
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            //执行查询
            rs = pst.executeQuery();
            //遍历结果集
            while (rs.next()) {
                user.setUserId(rs.getString("userId"));
                user.setPassword(rs.getString("password"));
                user.setUserName(rs.getString("userName"));
                user.setUserSex(rs.getInt("userSex"));
                user.setUserImg(rs.getString("userImg"));
                user.setDelTag(rs.getInt("delTag"));
            }
        }finally{
            DBUtil.close(rs,pst);
        }
        return user;
    }

    @Override
    public int getUserById(String userId) throws Exception{
        String sql = "SELECT * FROM user WHERE userId=?";
        User user = new User();
        int result = 0;
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            //执行查询
            rs = pst.executeQuery();
            if (rs == null){
                result = 0;
            }else{
                result= 1;
            }
        } finally{
            DBUtil.close(rs,pst);
        }
        return result;
    }

    @Override
    public int saveUser(String userId, String password, String userName, String userSex) throws Exception{
        String sql = "INSERT INTO user(userId,password,userName,userSex) VALUES(?,?,?,?)";
        int result = 0;
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);

            pst.setString(1,userId);
            pst.setString(2,password);
            pst.setString(3,userName);
            pst.setString(4,userSex);
            //执行更新
            result = pst.executeUpdate();
        } finally{
            DBUtil.close(rs,pst);
        }
        return result;
    }
}
